import timeFormat from '../function/timeFormat'

function init() {
	// 自动设置创建时间和更新时间
	window.$db.drafts.hook('creating', function (primaryKey, drafts) {
		// 设置创建时间
		drafts.createdAt = new Date().getTime();
		// 初始化更新时间为创建时间
		drafts.updatedAt = drafts.createdAt;
		// 创建时间
		drafts.createdTime = timeFormat(drafts.createdAt,'yyyy-mm-dd hh:MM:ss')
		drafts.updatedTime = timeFormat(drafts.updatedAt,'yyyy-mm-dd hh:MM:ss')
		
	});
	window.$db.drafts.hook('updating', function (modifications, primaryKey, obj, transaction) {
		// 设置更新时间
		modifications.updatedAt = new Date().getTime();
		modifications.updatedTime = timeFormat(modifications.updatedAt,'yyyy-mm-dd hh:MM:ss')
		
	});
	window.$db.drafts.findPageList = findPageList
	window.$db.drafts.addData = addData
	window.$db.drafts.deleteIds = deleteIds
	window.$db.drafts.updateData = updateData
}
// 分页查询
function findPageList({ size, current }) {
	return new Promise((resolve, reject) => {
		const pageQuery = $db.drafts
			.orderBy('createdAt').reverse() // 按createdAt降序排序
			.offset((current - 1) * size) // 设置偏移量
			.limit(size) // 限制每页的记录数
			.toArray()
			
		let countQuery = $db.drafts.count()
		Promise.all([pageQuery, countQuery]).then(results => {
			const data = results[0];
			const total = results[1];
			resolve({
				code: 0,
				data: {
					list: data,
					current,
					size,
					total
				}
			})

		}).catch(error => {
			reject({
				code: -2,
				error
			})
		});
	})
}
// 添加数据
function addData(req) {
	return new Promise((resolve, reject) => {
		$db.drafts.add(req).then(res=>{
			resolve({
				code: 0,
				msg:'添加成功'
			})
		}).catch(error => {
			reject({
				code: -2,
				error
			})
		});
	})
}
// 删除多条数据
function deleteIds(req) {
	return new Promise((resolve, reject) => {
		$db.drafts.bulkDelete(req.ids).then(res=>{
			resolve({
				code: 0,
				msg:'删除成功'
			})
		}).catch(error => {
			reject({
				code: -2,
				error
			})
		});
	})
}

// 编辑
function updateData({id,...req}) {
	return new Promise((resolve, reject) => {
		$db.drafts.update(id,req).then(res=>{
			resolve({
				code: 0,
				msg:'更新成功'
			})
		}).catch(error => {
			reject({
				code: -2,
				error
			})
		});
	})
}


export default {
	init
}